package com.comdo.newup_loan.bank;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.comdo.newup_loan.BankWebViewActivity;
import com.comdo.newup_loan.bank.bank.AppConfig;
import com.comdo.newup_loan.bank.bank.BankConfig;
import com.comdo.newup_loan.bank.bank.SignatureAlgorithm;
import com.comdo.newup_loan.bank.bank.SignatureUtils;
import com.comdo.newup_loan.comom.Config;
import com.comdo.newup_loan.util.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Headers;


public class BankUtils {
	private final static Logger logger = LoggerFactory
			.getLogger(BankUtils.class);

	/**
	 * 生成参数<br>
	 * 签名加密
	 */
	public static Map<String, String> createPostParam(String serviceName,
			Map<String, Object> reqDataMap, Context c)
			throws GeneralSecurityException {
		Map<String, String> result = new HashMap<String, String>();

		AppConfig config = AppConfig.getConfig(c);
		String privateStr = config.getPrivateKey();

		String reqData = JSON.toJSONString(reqDataMap);
		logger.debug("请求参数reqData:" + reqData);
		PrivateKey privateKey = SignatureUtils.getRsaPkcs8PrivateKey(Base64
				.decode(privateStr, Base64.DEFAULT));
		byte[] sign = SignatureUtils.sign(SignatureAlgorithm.SHA1WithRSA,
				privateKey, reqData);

		// 拼装网关参数
		result.put("serviceName", serviceName);
		result.put("platformNo", config.getPlatformNo());
		result.put("reqData", reqData);
		result.put("keySerial", config.getKeySerial());
		result.put("userDevice", BankConfig.MOBILE);
		result.put("sign", Base64.encodeToString(sign, Base64.DEFAULT));
		Log.e("result",result.toString());
		return result;
	}

	public static void verifySign(Headers response, String responseData,
								  Context c) throws Exception {

		Map<String, Object> respMap = JSON.parseObject(responseData);
		// 接口返回code!=0 || status!=SUCCESS时，不做验签处理
		if (!"0".equals(respMap.get("code"))
				|| !"SUCCESS".equals(respMap.get("status"))) {

			return;
		}
		AppConfig config = AppConfig.getConfig(c);
		// 校验返回报文
		String returnSign = response.get("sign");
		byte[] keyByte = Base64.decode(config.getLmPublicKey(), Base64.DEFAULT);
		byte[] signByte = Base64.decode(returnSign, Base64.DEFAULT);
		try {
			PublicKey publicKey = SignatureUtils.getRsaX509PublicKey(keyByte);

			boolean b = SignatureUtils.verify(SignatureAlgorithm.SHA1WithRSA,
					publicKey, responseData, signByte);
			if (!b) {
				throw new Exception("验签失败，sign与respData不匹配");
			}

			logger.info("sign success ...");
		} catch (InvalidKeySpecException e) {
			throw new InvalidKeySpecException("验签错误，生成商户公钥失败", e);
		} catch (NoSuchAlgorithmException e) {
			throw new NoSuchAlgorithmException("验签错误" + e.getMessage(), e);
		} catch (GeneralSecurityException e) {
			throw new GeneralSecurityException("验签错误" + e.getMessage(), e);
		}

	}

	/**
	 * 跳往新网银行网关页面
	 */
	public static void toWebView(String url, Activity activity) {
		if (!StringUtils.isNull(url)) {
			Intent intent = new Intent(activity, BankWebViewActivity.class);
			intent.putExtra("url", url);
			activity.startActivity(intent);
		} else {
			Toast.makeText(activity, "page not found", Toast.LENGTH_SHORT)
					.show();
		}
	}



	public static Boolean hasBankRegisterDialog() {
		if (Config.userInfo != null
				&& (Config.userInfo.getActivateAccount() == 1 || Config.userInfo
						.getRealNameCheck() == 0)) {
			return true;
		} else {
			return false;
		}

	}

	@SuppressLint("SimpleDateFormat")
	private static final DateFormat format = new SimpleDateFormat(
			"yyyyMMddHHmmssSSS");

	public static String createRequestNo() {
		String requestNo = format.format(new Date());
		return requestNo;
	}
}
